from time import gmtime, strftime
import pandas
import pprint
import numpy


def pd_to_dict(df):
    # filter out invalid recorder
    valid = ~df.iloc[:, 1].isnull()
    df = df[valid].copy()
    return list(zip(df.iloc[:, 0], numpy.cumsum(df.iloc[:, 1].astype(int))))


tiu_reg_bm1684x = "./BM1686_TPU_TIU_Reg6.5.xlsx"
dma_reg_bm1684x = "./GDMA_1686_DES_REG_v7.7.xlsx"

bdc_sheet_name = [
    "CONV",
    "sCONV",
    "MM",
    "sMM",
    "MM2",
    "sMM2",
    "CMP",
    "sCMP",
    "SFU",
    "sSFU",
    "VC",
    "sVC",
    "LIN",
    "sLIN",
    "AR",
    "sAR",
    "SEG",
    "sSEG",
    "PorD",
    "sPorD",
    "RQ&DQ",
    "sRQ&sDQ",
    "SG",
    "sSG",
    "SGL",
    "sSGL",
    "TRANS&BC",
    "sTRANS&sBC",
    "LAR",
    "SYS",
    "SYSID",
]
dma_sheet_name = [
    "DMA_tensor（0x000）",
    "DMA_matrix",
    "sDMA_matrix",
    "DMA_masked_select",
    "sDMA_masked_select ",
    "DMA_general",
    "sDMA_general",
    "DMA_cw_transpose",
    "DMA_nonzero",
    "sDMA_nonzero",
    "sDMA_sys",
    "DMA_gather",
    "DMA_scatter",
]

reg_bdc = pandas.read_excel(tiu_reg_bm1684x, sheet_name=bdc_sheet_name)
reg_dma = pandas.read_excel(dma_reg_bm1684x, sheet_name=dma_sheet_name)

cmd_reg = {}
for k, df in reg_bdc.items():
    cmd_reg[k] = pd_to_dict(df)

for k, df in reg_dma.items():
    cmd_reg[k] = pd_to_dict(df)

with open("regdef_1684x.py", "w") as fb:
    fb.write(f"# automatically generated by {__file__}\n\n")
    fb.write(f"# {strftime('%Y-%m-%d %H:%M:%S', gmtime())}\n\n")
    fb.write(f"# {tiu_reg_bm1684x}\n")
    fb.write(f"# {dma_reg_bm1684x}\n\n")
    fb.write("reg_def = ")
    pprint.pprint(cmd_reg, width=80, stream=fb)
